﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if !WINRT
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
#else
using Windows.UI.Core;
using Windows.UI.Xaml;

#endif

namespace MishraReader.Tools
{
    public class WpfApplication : IWpfApplication
    {
#if !WINRT
        private Dispatcher _dispatcher;
#else
        private CoreDispatcher _dispatcher;
#endif
        public TaskScheduler UiTaskScheduler { get; private set; }

        public void Initialize()
        {
#if !WINRT
            _dispatcher = Application.Current.Dispatcher;
#else
            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
#endif
            UiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        }

        public Task Invoke(Action action)
        {
#if !WINRT
            return _dispatcher.BeginInvoke(action).Task;
#else
            return _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).AsTask();
#endif
        }

        public void AddApplicationResources(Uri resourceDictionaryUri)
        {
            var rd = new ResourceDictionary
            {
                Source = resourceDictionaryUri
            };

            Application.Current.Resources.MergedDictionaries.Add(rd);
        }


        public void RefreshCommands()
        {
#if !WINRT
            CommandManager.InvalidateRequerySuggested();
#else
            // TODO: Determine the correct replacement for this
#endif
        }

        public void Shutdown()
        {
#if !WINRT
            Application.Current.Shutdown(0);
#else
            Application.Current.Exit();
#endif
        }
    }
}
